<template>
  <div class="medical-record-templates">
    <div class="page-header">
      <h2>病历模板管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateTemplate">
          <el-icon><Plus /></el-icon>
          新建模板
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <div class="filter-content">
        <el-form :model="filterForm" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="模板名称">
                <el-input
                  v-model="filterForm.name"
                  placeholder="请输入模板名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="适用科室">
                <el-select
                  v-model="filterForm.department"
                  placeholder="请选择科室"
                  clearable
                >
                  <el-option
                    v-for="dept in departmentOptions"
                    :key="dept.value"
                    :label="dept.label"
                    :value="dept.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="模板类型">
                <el-select
                  v-model="filterForm.type"
                  placeholder="请选择类型"
                  clearable
                >
                  <el-option
                    v-for="type in templateTypeOptions"
                    :key="type.value"
                    :label="type.label"
                    :value="type.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态">
                <el-select
                  v-model="filterForm.status"
                  placeholder="请选择状态"
                  clearable
                >
                  <el-option label="启用" value="active" />
                  <el-option label="停用" value="inactive" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="filter-actions">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 模板列表 -->
    <el-card>
      <template #header>
        <div class="table-header">
          <span>病历模板列表</span>
          <span class="total-count">共 {{ total }} 个模板</span>
        </div>
      </template>

      <el-table
        :data="templateList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="模板名称" min-width="180">
          <template #default="{ row }">
            <div class="template-name-cell">
              <el-icon class="template-icon"><Document /></el-icon>
              <span class="name-text">{{ row.name }}</span>
              <el-tag v-if="row.isDefault" type="success" size="small" class="default-tag">
                默认
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="模板描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="department" label="适用科室" width="120">
          <template #default="{ row }">
            <el-tag type="info" size="small">
              {{ getDepartmentText(row.department) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="模板类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTemplateTypeTagType(row.type)" size="small">
              {{ getTemplateTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageCount" label="使用次数" width="100" align="center">
          <template #default="{ row }">
            <span class="usage-count">{{ row.usageCount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'" size="small">
              {{ row.status === 'active' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleUseTemplate(row)"
            >
              使用
            </el-button>
            <el-button
              type="success"
              link
              size="small"
              @click="handleEditTemplate(row)"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleSetDefault(row)"
              :disabled="row.isDefault"
            >
              设默认
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDeleteTemplate(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 模板预览抽屉 -->
    <el-drawer
      v-model="previewDrawerVisible"
      title="模板预览"
      direction="rtl"
      size="80%"
    >
      <TemplatePreview
        v-if="previewDrawerVisible"
        :template-data="selectedTemplate"
        @use-template="handleUseFromPreview"
      />
    </el-drawer>

    <!-- 模板编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEditMode ? '编辑模板' : '新建模板'"
      width="90%"
      top="5vh"
      class="template-edit-dialog"
    >
      <TemplateEdit
        v-if="editDialogVisible"
        :template-data="editingTemplate"
        :is-edit="isEditMode"
        @saved="handleTemplateSaved"
        @cancel="editDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Document } from '@element-plus/icons-vue'
import TemplatePreview from '@/components/doctor/TemplatePreview.vue'
import TemplateEdit from '@/components/doctor/TemplateEdit.vue'

// 响应式数据
const loading = ref(false)
const total = ref(0)
const previewDrawerVisible = ref(false)
const editDialogVisible = ref(false)
const isEditMode = ref(false)
const selectedTemplate = ref(null)
const editingTemplate = ref(null)

// 筛选表单
const filterForm = reactive({
  name: '',
  department: '',
  type: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})

// 选项数据
const departmentOptions = [
  { label: '内科', value: 'internal' },
  { label: '外科', value: 'surgery' },
  { label: '儿科', value: 'pediatrics' },
  { label: '妇产科', value: 'obstetrics' },
  { label: '眼科', value: 'ophthalmology' },
  { label: '耳鼻喉科', value: 'ent' },
  { label: '皮肤科', value: 'dermatology' },
  { label: '中医科', value: 'tcm' }
]

const templateTypeOptions = [
  { label: '初诊病历', value: 'initial' },
  { label: '复诊病历', value: 'followup' },
  { label: '急诊病历', value: 'emergency' },
  { label: '住院病历', value: 'inpatient' },
  { label: '体检病历', value: 'physical' }
]

// 模板列表数据
const templateList = ref([
  {
    id: 1,
    name: '内科初诊通用模板',
    description: '适用于内科初诊患者的通用病历模板',
    department: 'internal',
    type: 'initial',
    usageCount: 156,
    status: 'active',
    isDefault: true,
    updateTime: '2024-03-15 10:30:00',
    content: {
      chiefComplaint: '患者主诉...',
      presentIllness: '现病史描述...',
      pastHistory: '既往史...',
      physicalExam: '体格检查...',
      diagnosis: '初步诊断...',
      treatmentPlan: '治疗方案...'
    }
  },
  {
    id: 2,
    name: '高血压复诊模板',
    description: '专门用于高血压患者复诊的病历模板',
    department: 'internal',
    type: 'followup',
    usageCount: 89,
    status: 'active',
    isDefault: false,
    updateTime: '2024-03-14 16:20:00',
    content: {
      chiefComplaint: '血压控制情况...',
      presentIllness: '近期症状变化...',
      vitalSigns: '血压、心率等生命体征',
      medicationEffect: '药物疗效评估',
      diagnosis: '高血压病情评估',
      treatmentPlan: '调整用药方案...'
    }
  },
  {
    id: 3,
    name: '儿科常见病模板',
    description: '适用于儿科常见疾病的病历模板',
    department: 'pediatrics',
    type: 'initial',
    usageCount: 234,
    status: 'active',
    isDefault: true,
    updateTime: '2024-03-13 14:15:00',
    content: {
      chiefComplaint: '患儿主诉...',
      presentIllness: '发病过程...',
      vaccinationHistory: '疫苗接种史',
      growthDevelopment: '生长发育情况',
      diagnosis: '儿科疾病诊断',
      treatmentPlan: '儿科治疗方案...'
    }
  },
  {
    id: 4,
    name: '外科术前评估模板',
    description: '外科手术前的患者评估模板',
    department: 'surgery',
    type: 'initial',
    usageCount: 67,
    status: 'active',
    isDefault: false,
    updateTime: '2024-03-12 09:45:00',
    content: {
      chiefComplaint: '手术适应症...',
      presentIllness: '疾病发展过程...',
      surgicalHistory: '手术史',
      anesthesiaAssessment: '麻醉评估',
      diagnosis: '手术诊断',
      surgicalPlan: '手术方案...'
    }
  },
  {
    id: 5,
    name: '中医辨证模板',
    description: '中医辨证论治专用模板',
    department: 'tcm',
    type: 'initial',
    usageCount: 45,
    status: 'inactive',
    isDefault: false,
    updateTime: '2024-03-10 11:20:00',
    content: {
      chiefComplaint: '中医主诉...',
      tonguePulse: '舌象脉象',
      syndromeDifferentiation: '辨证分型',
      tcmDiagnosis: '中医诊断',
      treatmentPrinciple: '治则治法',
      prescription: '方药组成...'
    }
  }
])

// 方法
const handleSearch = () => {
  pagination.currentPage = 1
  loadTemplateList()
}

const handleReset = () => {
  Object.assign(filterForm, {
    name: '',
    department: '',
    type: '',
    status: ''
  })
  handleSearch()
}

const loadTemplateList = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取模板列表
    // const response = await templateApi.getList({
    //   ...filterForm,
    //   page: pagination.currentPage,
    //   size: pagination.pageSize
    // })
    // templateList.value = response.data
    // total.value = response.total
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    total.value = templateList.value.length
  } catch (error) {
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

const refreshData = () => {
  loadTemplateList()
}

const handleCreateTemplate = () => {
  isEditMode.value = false
  editingTemplate.value = null
  editDialogVisible.value = true
}

const handleUseTemplate = (template) => {
  selectedTemplate.value = template
  previewDrawerVisible.value = true
}

const handleEditTemplate = (template) => {
  isEditMode.value = true
  editingTemplate.value = { ...template }
  editDialogVisible.value = true
}

const handleSetDefault = async (template) => {
  try {
    await ElMessageBox.confirm(
      `确定要将"${template.name}"设为默认模板吗？`,
      '设置默认模板',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用API设置默认模板
    // await templateApi.setDefault(template.id)
    
    // 更新本地数据
    templateList.value.forEach(t => {
      t.isDefault = t.id === template.id
    })
    
    ElMessage.success('设置默认模板成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('设置默认模板失败')
    }
  }
}

const handleDeleteTemplate = async (template) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除"${template.name}"模板吗？此操作不可恢复。`,
      '删除模板',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用API删除模板
    // await templateApi.delete(template.id)
    
    // 更新本地数据
    templateList.value = templateList.value.filter(t => t.id !== template.id)
    total.value = templateList.value.length
    
    ElMessage.success('删除模板成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除模板失败')
    }
  }
}

const handleUseFromPreview = (template) => {
  ElMessage.success(`开始使用模板：${template.name}`)
  previewDrawerVisible.value = false
  // TODO: 跳转到病历创建页面，并应用模板
}

const handleTemplateSaved = (template) => {
  editDialogVisible.value = false
  if (isEditMode.value) {
    ElMessage.success('模板更新成功')
  } else {
    ElMessage.success('模板创建成功')
  }
  refreshData()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadTemplateList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadTemplateList()
}

const getDepartmentText = (department) => {
  const dept = departmentOptions.find(d => d.value === department)
  return dept ? dept.label : department
}

const getTemplateTypeText = (type) => {
  const templateType = templateTypeOptions.find(t => t.value === type)
  return templateType ? templateType.label : type
}

const getTemplateTypeTagType = (type) => {
  const typeMap = {
    initial: 'primary',
    followup: 'success',
    emergency: 'warning',
    inpatient: 'danger',
    physical: 'info'
  }
  return typeMap[type] || 'info'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return dateString.split(' ')[0] // 只显示日期部分
}

// 生命周期
onMounted(() => {
  loadTemplateList()
})
</script>

<style lang="scss" scoped>
.medical-record-templates {
  padding: 20px;
  background: #f5f7fa;
  height: 0;  // 添加这行
  min-height: 100%;  // 添加这行
  overflow-y: auto;  // 确保有这行
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
  }
}

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-content {
  .filter-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 10px;
  }
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-count {
  color: #909399;
  font-size: 14px;
}

.template-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.template-icon {
  color: #409eff;
  font-size: 16px;
}

.name-text {
  font-weight: 500;
}

.default-tag {
  margin-left: 4px;
}

.usage-count {
  font-weight: 600;
  color: #409eff;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.template-edit-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

:deep(.el-table__row) {
  .template-name-cell {
    .name-text {
      transition: color 0.3s;
    }
  }
  
  &:hover {
    .template-name-cell {
      .name-text {
        color: #409eff;
      }
    }
  }
}
</style>